// Strategy Analytics API Service
// This service provides functions to fetch data for the Strategy Analytics Dashboard
// Currently using JSON files, but can be easily replaced with real API calls

export interface AnalyticsApiResponse<T> {
  success: boolean;
  data: T;
  message?: string;
}

export interface UsageTrendResponse {
  labels: string[];
  data: number[];
}

export interface ConversionRateResponse {
  type: string;
  rate: number;
}

export interface ScatterDataPoint {
  x: number;
  y: number;
}

// JSON data structure interface
interface StrategyAnalyticsJsonData {
  customerSegments: Array<{ name: string; value: string }>;
  strategyTypes: Array<{ name: string; value: string }>;
  workScenarios: Array<{ name: string; count: number }>;
  bubbleChartData: Array<{
    name: string;
    data: Array<{ x: string; y: number; z: number }>;
  }>;
  businessScenarioMap: Record<string, number>;
  businessScenarioLabels: string[];
  topStrategiesData: Array<{ name: string; count: number }>;
  strategyTypeDistribution: number[];
  strategySourceDistribution: number[];
  strategyUsageBySegment: Array<{
    segment: string;
    topStrategy: string;
    dailyAverage: number;
    mainScenario: string;
  }>;
  alertsData: Array<{
    type: 'warning' | 'error' | 'info';
    title: string;
    description: string;
  }>;
}

// Helper function to fetch JSON data
const fetchJsonData = async (url: string): Promise<StrategyAnalyticsJsonData> => {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error(`Failed to fetch data from ${url}`);
  }
  return response.json();
};

// Helper function to generate dynamic data based on period
const generateUsageTrendData = (days: number = 7) => {
  const data = [];
  const labels = [];
  
  for (let i = days - 1; i >= 0; i--) {
    const date = new Date();
    date.setDate(date.getDate() - i);
    labels.push(`${date.getMonth() + 1}/${date.getDate()}`);
    data.push(Math.floor(Math.random() * 1000) + 500);
  }
  
  return { labels, data };
};

const generateConversionFunnelData = (period: number = 7) => {
  const multiplier = period === 7 ? 1 : period === 30 ? 5 : 15;
  return [
    { stage: '策略触发', count: 5230 * multiplier },
    { stage: '客户点击', count: 3890 * multiplier },
    { stage: '咨询跟进', count: 2150 * multiplier },
    { stage: '产品认购', count: 850 * multiplier }
  ];
};

const generateConversionRateData = (period: number = 7) => {
  const baseRates = period === 7 ? [25, 18, 12, 8] : period === 30 ? [22, 19, 11, 9] : [20, 17, 13, 7];
  return [
    { type: '专家解读框架', rate: baseRates[0] },
    { type: '资产配置策略', rate: baseRates[1] },
    { type: '营销策略', rate: baseRates[2] },
    { type: '经营引导策略', rate: baseRates[3] }
  ];
};

const generateScatterData = (period: number = 7) => {
  const baseData = period === 7 
    ? [{ x: 95, y: 5 }, { x: 120, y: 18 }, { x: 35, y: 25 }, { x: 80, y: 22 }, { x: 250, y: 2 }]
    : period === 30
    ? [{ x: 450, y: 4 }, { x: 550, y: 15 }, { x: 150, y: 28 }, { x: 380, y: 20 }, { x: 1100, y: 1.5 }]
    : [{ x: 1500, y: 3.5 }, { x: 1800, y: 14 }, { x: 500, y: 26 }, { x: 1200, y: 19 }, { x: 3500, y: 1 }];
  
  return baseData;
};

/**
 * Strategy Coverage API calls
 */
export const strategyCoverageApi = {
  // Get bubble chart data for customer segments vs strategy types
  async getBubbleChartData(): Promise<AnalyticsApiResponse<any[]>> {
    try {
      const data = await fetchJsonData('/data/strategyAnalyticsData.json');
      return { success: true, data: data.bubbleChartData };
    } catch (error) {
      console.error('Error fetching bubble chart data:', error);
      return { success: false, data: [], message: 'Failed to fetch bubble chart data' };
    }
  },

  // Get scenario distribution data
  async getScenarioDistribution(): Promise<AnalyticsApiResponse<any[]>> {
    try {
      const data = await fetchJsonData('/data/strategyAnalyticsData.json');
      return { success: true, data: data.workScenarios };
    } catch (error) {
      console.error('Error fetching scenario data:', error);
      return { success: false, data: [], message: 'Failed to fetch scenario data' };
    }
  },

  // Get strategy type distribution
  async getStrategyTypeDistribution(): Promise<AnalyticsApiResponse<{
    types: any[];
    distribution: number[];
  }>> {
    try {
      const data = await fetchJsonData('/data/strategyAnalyticsData.json');
      return { 
        success: true, 
        data: { 
          types: data.strategyTypes, 
          distribution: data.strategyTypeDistribution 
        } 
      };
    } catch (error) {
      console.error('Error fetching strategy type data:', error);
      return { success: false, data: { types: [], distribution: [] }, message: 'Failed to fetch strategy type data' };
    }
  }
};

/**
 * Strategy Usage API calls
 */
export const strategyUsageApi = {
  // Get usage trend data
  async getUsageTrend(period: 7 | 30 | 90 = 7): Promise<AnalyticsApiResponse<UsageTrendResponse>> {
    try {
      const data = generateUsageTrendData(period);
      return { success: true, data };
    } catch (error) {
      console.error('Error fetching usage trend data:', error);
      return { success: false, data: { labels: [], data: [] }, message: 'Failed to fetch usage trend data' };
    }
  },

  // Get top strategies data
  async getTopStrategies(limit: number = 10): Promise<AnalyticsApiResponse<any[]>> {
    try {
      const data = await fetchJsonData('/data/strategyAnalyticsData.json');
      return { success: true, data: data.topStrategiesData.slice(0, limit) };
    } catch (error) {
      console.error('Error fetching top strategies data:', error);
      return { success: false, data: [], message: 'Failed to fetch top strategies data' };
    }
  },

  // Get strategy source distribution
  async getSourceDistribution(): Promise<AnalyticsApiResponse<{
    labels: string[];
    data: number[];
  }>> {
    try {
      const data = await fetchJsonData('/data/strategyAnalyticsData.json');
      return { 
        success: true, 
        data: { 
          labels: ['理财师主动调用', '系统自动召回'], 
          data: data.strategySourceDistribution 
        } 
      };
    } catch (error) {
      console.error('Error fetching source distribution data:', error);
      return { success: false, data: { labels: [], data: [] }, message: 'Failed to fetch source distribution data' };
    }
  },

  // Get usage by customer segment
  async getUsageBySegment(): Promise<AnalyticsApiResponse<any[]>> {
    try {
      const data = await fetchJsonData('/data/strategyAnalyticsData.json');
      return { success: true, data: data.strategyUsageBySegment };
    } catch (error) {
      console.error('Error fetching usage by segment data:', error);
      return { success: false, data: [], message: 'Failed to fetch usage by segment data' };
    }
  }
};

/**
 * Conversion & Effect API calls
 */
export const conversionAnalyticsApi = {
  // Get conversion funnel data
  async getConversionFunnel(period: 7 | 30 | 90 = 7): Promise<AnalyticsApiResponse<any[]>> {
    try {
      const data = generateConversionFunnelData(period);
      return { success: true, data };
    } catch (error) {
      console.error('Error fetching conversion funnel data:', error);
      return { success: false, data: [], message: 'Failed to fetch conversion funnel data' };
    }
  },

  // Get conversion rates by strategy type
  async getConversionRates(period: 7 | 30 | 90 = 7): Promise<AnalyticsApiResponse<ConversionRateResponse[]>> {
    try {
      const data = generateConversionRateData(period);
      return { success: true, data };
    } catch (error) {
      console.error('Error fetching conversion rates data:', error);
      return { success: false, data: [], message: 'Failed to fetch conversion rates data' };
    }
  },

  // Get scatter plot data for frequency vs conversion
  async getFrequencyVsConversion(period: 7 | 30 | 90 = 7): Promise<AnalyticsApiResponse<ScatterDataPoint[]>> {
    try {
      const data = generateScatterData(period);
      return { success: true, data };
    } catch (error) {
      console.error('Error fetching frequency vs conversion data:', error);
      return { success: false, data: [], message: 'Failed to fetch frequency vs conversion data' };
    }
  }
};

/**
 * Alerts & Suggestions API calls
 */
export const alertsApi = {
  // Get current alerts and suggestions
  async getAlerts(): Promise<AnalyticsApiResponse<any[]>> {
    try {
      const data = await fetchJsonData('/data/strategyAnalyticsData.json');
      return { success: true, data: data.alertsData };
    } catch (error) {
      console.error('Error fetching alerts data:', error);
      return { success: false, data: [], message: 'Failed to fetch alerts data' };
    }
  }
};

/**
 * Combined API service for the entire dashboard
 */
export const strategyAnalyticsService = {
  coverage: strategyCoverageApi,
  usage: strategyUsageApi,
  conversion: conversionAnalyticsApi,
  alerts: alertsApi
};

export default strategyAnalyticsService; 